import 'dart:async';
import 'dart:convert';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flustars/flustars.dart';
import 'package:flutter/material.dart';
import 'package:flutter_rider/api/api.dart';
import 'package:flutter_rider/event/location_event.dart';
import 'package:flutter_rider/generated/assets.dart';
import 'package:flutter_rider/kit/loc_kit.dart';
import 'package:flutter_rider/main.dart';
import 'package:flutter_rider/main/widgets/dialog/alert_dialog.dart';
import 'package:flutter_rider/main/widgets/ext/u_layout.dart';
import 'package:flutter_rider/main/widgets/ext/u_text.dart';
import 'package:flutter_rider/main/widgets/ui_constant.dart';
import 'package:flutter_rider/module/login/page/login_page.dart';
import 'package:flutter_rider/module/login/provider/user_provider.dart';
import 'package:flutter_rider/module/mine/mine_router.dart';
import 'package:flutter_rider/module/mine/provider/mine_provider.dart';
import 'package:flutter_rider/module/mine/widgets/image_text_widget.dart';
import 'package:flutter_rider/routers/fluro_navigator.dart';
import 'package:flutter_rider/utils/calculate_utils.dart';
import 'package:flutter_rider/utils/log.dart';
import 'package:flutter_rider/utils/screen_fit.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:expandable_text/expandable_text.dart';
import 'package:flutter_rider/app.dart';
import 'package:flutter_rider/kit/app_update_kit.dart';
import 'package:shared_preferences/shared_preferences.dart';

class MinePage extends ConsumerStatefulWidget {
  @override
  ConsumerState createState() {
    return MinePageState();
  }
}

class MinePageState extends ConsumerState<MinePage> {
  // late StreamSubscription _locationEvent;
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    // _locationEvent = eventBus.on<LocationEvent>().listen((event) {
    //   setState(() {});
    // });

    // ref.read(isWorkListenProvider);
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    // _locationEvent.cancel();
  }

  @override
  Widget build(BuildContext context) {
    return Material(
        color: UIColor.color_main,
        child: Container(
            width: double.infinity,
            height: MediaQuery.of(context).size.height,
            child: SingleChildScrollView(
                child: Stack(children: [
              Column(children: [
                Container(
                    color: UIColor.color_primary,
                    child: Column(
                      children: [
                        App.isLandscape
                            ? 12.hspace
                            : ScreenUtil.getInstance().statusBarHeight.hspace,
                        12.hspace,
                        Row(children: [
                          16.wspace,
                          _workWidget(),
                          const Spacer(),
                          _newsWidget(),
                          16.wspace,
                        ]),
                        16.hspace,
                        _avatarInfoWidget(),
                        // 16.hspace,
                        // _positionInfoWidget(),
                        16.hspace,
                        _recToolsTitleWidget(),
                      ],
                    )),
                ref.watch(isShowOperatorProvider.state).state
                    ? _recOperatorToolsWidget()
                    : _recToolsWidget(),
              ]),
              32.hspace,
              _renderLogout(),
            ]))));
  }

  Widget _workWidget() {
    return Container(
      width: 86.rpx,
      height: 32.rpx,
      decoration: BoxDecoration(
          // color: UIColor.color_content,
          border: Border.all(color: Colors.white, width: 0.5.rpx),
          borderRadius: BorderRadius.circular(16.rpx)),
      child: Row(
          // crossAxisAlignment: CrossAxisAlignment.center,
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Consumer(builder: (context, ref, child) {
              return UText.get(ref.watch(isWorkProvider) ? "工作中" : "休息中",
                  UIColor.color_bg, 14.rpx);
            }),
            2.wspace,
            SvgPicture.asset(
              Assets.imageMineDown,
              width: 16.rpx,
              height: 16.rpx,
            )
          ]),
    ).onTap(() {
      // var isWork = ref.read(isWorkProvider);
      CustomAlertDialog.showWorkDialog(context);
    });
  }

  Widget _newsWidget() {
    return Container(
        width: 27.rpx,
        height: 27.rpx,
        // color: Colors.red,
        child: Stack(
          children: [
            Positioned(
                bottom: 0.rpx,
                left: 0.rpx,
                child: SvgPicture.asset(Assets.imageMineNotification,
                    width: 24.rpx, height: 24.rpx)),
            // Positioned(
            //     top: 0.rpx,
            //     right: 0.rpx,
            //     child: Container(
            //       width: 10.rpx,
            //       height: 10.rpx,
            //       //color: UIColor.color_none,
            //       decoration: BoxDecoration(
            //           color: UIColor.color_none,
            //           borderRadius: BorderRadius.circular(5.rpx)),
            //     ))
          ],
        ).onTap(() {
          Log.i("点击了消息");
          NavigatorUtils.push(context, MineRouter.messagePage);
        }));
  }

  Widget _avatarInfoWidget() {
    return Consumer(builder: (context, ref, child) {
      var user = ref.read(userModelProvider);
      var mobile = TextUtil.formatDigitPatternEnd(user.mobile);
      return Container(
        // color: Colors.red,
        //width: ScreenUtil.getInstance().screenWidth,
        height: 64.rpx,
        child: Row(
          mainAxisAlignment: MainAxisAlignment.start,
          children: [
            16.wspace,
            Container(
              decoration: BoxDecoration(
                  color: UIColor.color_content,
                  borderRadius: BorderRadius.circular(32.rpx)),
              child: user.avatar.isNotEmpty
                  ? CachedNetworkImage(
                      imageUrl: user.avatar,
                      placeholder: (context, url) =>
                          const CircularProgressIndicator(),
                      errorWidget: (context, url, error) => SvgPicture.asset(
                          Assets.imageMineAvatar,
                          width: 64.rpx,
                          height: 64.rpx),
                    )
                  : SvgPicture.asset(Assets.imageMineAvatar,
                      width: 64.rpx, height: 64.rpx),
            ),
            12.wspace,
            Column(
              // mainAxisAlignment: MainAxisAlignment.start,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  children: [
                    Container(
                      constraints: BoxConstraints(
                          maxWidth: ScreenUtil.getInstance().screenWidth / 3),
                      child: Text(
                        user.name,
                        maxLines: 1,
                        style: TextStyle(
                            color: UIColor.color_content,
                            fontSize: 20.rpx,
                            fontWeight: FontWeight.bold,
                            overflow: TextOverflow.ellipsis),
                      ),
                    ),
                    8.wspace,
                    Container(
                      constraints: BoxConstraints(
                          maxWidth: ScreenUtil.getInstance().screenWidth / 3),
                      decoration: BoxDecoration(
                          color: UIColor.color_tagbg,
                          borderRadius: BorderRadius.circular(16.rpx)),
                      child: Text(
                        user.role_name,
                        maxLines: 1,
                        style: TextStyle(
                            color: UIColor.color_content,
                            fontSize: 12.rpx,
                            fontWeight: FontWeight.bold,
                            overflow: TextOverflow.ellipsis),
                      ).padding(EdgeInsets.only(
                          top: 4.rpx,
                          bottom: 4.rpx,
                          left: 12.rpx,
                          right: 12.rpx)),
                    )
                  ],
                ),
                4.hspace,
                UText.get(mobile, UIColor.color_content, 14.rpx)
              ],
            ),
          ],
        ),
      );
    });
  }

  Widget _positionInfoWidget() {
    var address = LocKit.instance.getData()["address"] ?? "未知地址,定位失败";
    return SizedBox(
        width: double.infinity,
        child: Column(children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.start,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              16.wspace,
              SvgPicture.asset(Assets.imageMineMap,
                      width: 16.rpx, height: 16.rpx)
                  .padding(EdgeInsets.only(top: 3.rpx)),
              4.wspace,
              UText.get("所属区域：", UIColor.color_content, 14.rpx),
            ],
          ),
          Container(
              width: double.infinity,
              margin: EdgeInsets.only(left: 36.rpx, right: 36.rpx, top: 4.rpx),
              child: ExpandableText(
                address,
                expandText: '展开',
                collapseText: '收起',
                maxLines: 3,
                style:
                    TextStyle(color: UIColor.color_content, fontSize: 12.rpx),
                linkStyle: TextStyle(
                    decoration: TextDecoration.underline,
                    color: UIColor.color_content,
                    fontSize: 12.rpx,
                    fontWeight: FontWeight.bold),
                onExpandedChanged: (change) {
                  if (change) {
                    // var h = Calculate.calculateTextHeight(
                    //     address, 12.rpx, FontWeight.normal, textW, 99);
                    // Log.i("展开高度为：$h");
                    // _addressHeight = h;
                  } else {
                    Log.i("收起");
                    // _addressHeight = 44.rpx;
                  }
                },
              ))
        ]));
  }

  Widget _recToolsTitleWidget() {
    return Container(
      width: double.infinity,
      height: 40.rpx,
      margin: EdgeInsets.symmetric(horizontal: 12.rpx),
      decoration: BoxDecoration(
        color: UIColor.colorWhile09,
        boxShadow: [
          BoxShadow(offset: Offset(0.rpx, 2.rpx), color: UIColor.color_shadow2)
        ],
        borderRadius: BorderRadius.only(
            topLeft: Radius.circular(12.rpx),
            topRight: Radius.circular(12.rpx)),
      ),
      child: UText.get("推荐工具", UIColor.color_black, 16.rpx, fw: FontWeight.bold)
          .padding(EdgeInsets.only(top: 16.rpx, left: 16.rpx)),
    );
  }

  Widget _recOperatorToolsWidget() {
    return Container(
      width: double.infinity,
      // height: 92.rpx,
      margin: EdgeInsets.symmetric(horizontal: 12.rpx),
      decoration: BoxDecoration(
        color: UIColor.colorWhile09,
        boxShadow: [
          BoxShadow(offset: Offset(0.rpx, 2.rpx), color: UIColor.color_shadow2)
        ],
        borderRadius: BorderRadius.only(
            bottomLeft: Radius.circular(12.rpx),
            bottomRight: Radius.circular(12.rpx)),
      ),
      // height: 64.rpx,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          24.hspace,
          Row(
            // mainAxisSize: MainAxisSize.max,
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            // //交叉轴的布局方式，对于column来说就是水平方向的布局方式
            // crossAxisAlignment: CrossAxisAlignment.center,
            // //就是子child的垂直布局方向，向上还是向下
            // verticalDirection: VerticalDirection.down,
            children: [
              ImageTextWidget("调车日志", Assets.imageMineNote,
                      onTap: _shuntingLogClick, pixel: 24.rpx)
                  .expand,
              ImageTextWidget("场外车辆", Assets.imageMineTruckFast,
                      onTap: _outsideCarClick, pixel: 24.rpx)
                  .expand,
              ImageTextWidget("屏幕方向", Assets.imageMineBitcoinConvert,
                      onTap: _changeLandscapeClick, pixel: 24.rpx)
                  .expand,
              ImageTextWidget("操作员管理", Assets.imageUserOctagon,
                      onTap: _userOctagonClick, pixel: 24.rpx)
                  .expand,
            ],
          ),
          16.hspace,
          Row(
            // mainAxisSize: MainAxisSize.max,
            // mainAxisAlignment: MainAxisAlignment.spaceBetween,
            // //交叉轴的布局方式，对于column来说就是水平方向的布局方式
            // crossAxisAlignment: CrossAxisAlignment.center,
            // //就是子child的垂直布局方向，向上还是向下
            // verticalDirection: VerticalDirection.down,
            children: [
              Expanded(
                  flex: 1,
                  child: ImageTextWidget("当前版本", Assets.imageMineInformation,
                      onTap: _versionClick, pixel: 24.rpx)),
              Expanded(flex: 3, child: Container()),
            ],
          ),
          16.hspace,
        ],
      ),
    );
  }

  Widget _recToolsWidget() {
    return Container(
      width: double.infinity,
      // height: 92.rpx,
      margin: EdgeInsets.symmetric(horizontal: 12.rpx),
      decoration: BoxDecoration(
        color: UIColor.colorWhile09,
        boxShadow: [
          BoxShadow(offset: Offset(0.rpx, 2.rpx), color: UIColor.color_shadow2)
        ],
        borderRadius: BorderRadius.only(
            bottomLeft: Radius.circular(12.rpx),
            bottomRight: Radius.circular(12.rpx)),
      ),
      // height: 64.rpx,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          24.hspace,
          Row(
            // mainAxisSize: MainAxisSize.max,
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            // //交叉轴的布局方式，对于column来说就是水平方向的布局方式
            // crossAxisAlignment: CrossAxisAlignment.center,
            // //就是子child的垂直布局方向，向上还是向下
            // verticalDirection: VerticalDirection.down,
            children: [
              ImageTextWidget("调车日志", Assets.imageMineNote,
                      onTap: _shuntingLogClick, pixel: 24.rpx)
                  .expand,
              ImageTextWidget("场外车辆", Assets.imageMineTruckFast,
                      onTap: _outsideCarClick, pixel: 24.rpx)
                  .expand,
              ImageTextWidget("屏幕方向", Assets.imageMineBitcoinConvert,
                      onTap: _changeLandscapeClick, pixel: 24.rpx)
                  .expand,
              ImageTextWidget("当前版本", Assets.imageMineInformation,
                      onTap: _versionClick, pixel: 24.rpx)
                  .expand,
            ],
          ),
          16.hspace,
        ],
      ),
    );
  }

  _shuntingLogClick() {
    Log.i("调车日志");
    NavigatorUtils.push(context, MineRouter.shuntimeLogPage);
  }

  _outsideCarClick() {
    Log.i("场外车辆");
    NavigatorUtils.push(context, MineRouter.outsideCarPage);
  }

  _changeLandscapeClick() {
    Log.i("屏幕方向");
    var tip = App.isLandscape ? "确定切换屏幕方向为竖屏?" : "确定切换屏幕方向为横屏?";
    CustomAlertDialog.show(context, content: tip, onConfirm: () {
      App.setScreenLandscape(!App.isLandscape);
      setState(() {});
    });
  }

  _userOctagonClick() {
    Log.i("操作员管理");
    NavigatorUtils.push(context, MineRouter.operatorManagePage);
  }

  _versionClick() {
    Log.i("当前版本");
    AppUpdateKit.instance.check(context, true);
  }

  Widget _renderLogout() {
    return Container(
        width: double.infinity,
        padding: EdgeInsets.only(
            top: App.isLandscape
                ? MediaQuery.of(context).size.height
                : MediaQuery.of(context).size.height -
                    ScreenUtil.getInstance().bottomBarHeight -
                    130.rpx,
            bottom: 30.rpx),
        child: Padding(
          child: UText.getBkButton(
            "退出登录",
            16.rpx,
            width: double.infinity,
            height: 48.rpx,
            bkColor: UIColor.color_primary,
            radius: 24.rpx,
            onPressed: () {
              _onClickLogout();
            },
          ),
          padding: EdgeInsets.symmetric(horizontal: 12.rpx),
        ));
  }

  _onClickLogout() {
    CustomAlertDialog.show(context, content: "确定退出登录?", onConfirm: () {
      Api.logout();
      Navigator.pushAndRemoveUntil(context, MaterialPageRoute(
        builder: (context) {
          return LoginPage();
        },
      ), (route) => false);
    });
  }
}
